//
//  HappyPlayController.m
//  HappyBaby
//
//  Created by 华哥 on 15/11/23.
//  Copyright © 2015年 华哥. All rights reserved.
//

#import "HappyPlayController.h"
#import "HappyPlayCell.h"
#import "TableHeaderView.h"
#import "Define.h"
#import "DetailController.h"
#import "NetWorkState.h"
#import "UILabel+AlertViewAutoDisappear.h"
#import "CarouselFigureModel.h"
#import "HappyModel.h"
#import "CheckMoreController.h"
#import "SegmentController.h"
//
#import "LoginController.h"

@interface HappyPlayController ()<UITableViewDataSource, UITableViewDelegate, HappyPlayCellDelegate, CarouselFigureDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) TableHeaderView *tableHeader;

// 装载轮播图model的数组
@property (nonatomic, strong) NSMutableArray *carouseArray;
// 装载section下model的数组
@property (nonatomic, strong) NSMutableArray *happyArray;

@end

static NSString *cellIdentifier = @"cell";

@implementation HappyPlayController
{
    CGFloat _scaleY;
    CGFloat _scaleX;
}

// carouseArray懒加载
- (NSMutableArray *)carouseArray
{
    if (_carouseArray == nil) {
        self.carouseArray = [NSMutableArray array];
    }
    return _carouseArray;
}
// happyArray懒加载
- (NSMutableArray *)happyArray
{
    if (_happyArray == nil) {
        self.happyArray = [NSMutableArray array];
    }
    return _happyArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"宝贝好玩";
    
    // 屏幕适配比例
    _scaleY = kScreenHeight / 667;
    _scaleX = kScreenWidth / 375;
    
    // 测试登录界面的Button
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"login" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtn)];
    self.navigationItem.rightBarButtonItem = right;
    
    
    
    CGFloat height = 310 * kScreenHeight / 667;
    self.tableHeader = [[TableHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, height)];
    // 给carousel设置代理 为的是点击跳转到详情界面
    self.tableHeader.carousel.delegate = self;
    // 给tableHeader.button 添加方法
    for (UIButton *button in self.tableHeader.buttonArray) {
        [button addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
    }
    

    self.tableView.tableHeaderView = self.tableHeader;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
     
    // 注册cell
    [self.tableView registerClass:[HappyPlayCell class] forCellReuseIdentifier:cellIdentifier];
    
    //轮播图数据请求链接： http://api.bbwansha.com:8080/v22/index.php/Home/misc/banners
    //happy请求链接：http://api.bbwansha.com:8080/v22/index.php/Home/bbwspost/page1   //page不同可用于请求不同数据userid=0&page=2&age=-1
    // 创建请求链接
    NSURL *carouseUrl = [NSURL URLWithString:@"http://api.bbwansha.com:8080/v22/index.php/Home/misc/banners"];
    NSURL *happyUrl = [NSURL URLWithString:@"http://api.bbwansha.com:8080/v22/index.php/Home/bbwspost/page1"];
    
    // 请求数据前先判断一下网络状态
    if (![[NetWorkState shareInstance] reachAbility]) {
        [UILabel alertViewAutoDisappearWithTitle:@"网络状态不给力" viewController:self];
    }else{
        [[[NSURLSession sharedSession] dataTaskWithURL:carouseUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            // 测试请求数据
            // NSLog(@"dic = %@", dic);
            NSArray *carouseArray = [dic objectForKey:@"data"];
            // 将请求下来的数据赋值给model 创建model
            for (NSDictionary *modelDic in carouseArray) {
                CarouselFigureModel *carouseModel = [[CarouselFigureModel alloc] init];
                [carouseModel setValuesForKeysWithDictionary:modelDic];
                [self.carouseArray addObject:carouseModel];
            }
            
            // 在主线程中刷新
            dispatch_sync(dispatch_get_main_queue(), ^{
                _tableHeader.modelArray = self.carouseArray;
                [self.tableView reloadData];
                
            });
            
        }] resume];
        
        [[[NSURLSession sharedSession] dataTaskWithURL:happyUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil] ;
            NSDictionary *dataDic = [dic objectForKey:@"data"];
            // 根据字section1 section2取数据 对应得数组
            NSArray *section1Array = [dataDic objectForKey:@"section1"];
            NSArray *section2Array = [dataDic objectForKey:@"section2"];
            // 遍历分区一的 数组中的数据（字典）给model赋值
            NSMutableArray *subArray1 = [NSMutableArray array];
            for (NSDictionary *modleDic in section1Array) {
                HappyModel *happyModel = [[HappyModel alloc] init];
                [happyModel setValuesForKeysWithDictionary:modleDic];
                [subArray1 addObject:happyModel];
            }
            [self.happyArray addObject:subArray1];
            
           

            //遍历分区二的数组
            NSMutableArray *subArray2 = [NSMutableArray array];
            for (NSDictionary *modelDic in section2Array) {
                HappyModel *happyModel = [[HappyModel alloc] init];
                [happyModel setValuesForKeysWithDictionary:modelDic];
                [subArray2 addObject:happyModel];
            }
            [self.happyArray addObject:subArray2];
            
            // 主线程刷新
            dispatch_sync(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }] resume];
    }
    
}

- (void)rightBtn
{
    LoginController *loginVc = [[LoginController alloc] init];
    loginVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:loginVc animated:YES];
}


#pragma mark --返回分区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.happyArray.count;
}

// 分区下返回行
- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HappyPlayCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    // 给cell设置代理
    cell.delegate = self;
    
    if (indexPath.section == 0) {
        cell.postAuthor.text = @"今天玩儿啥";
        cell.modelArray = self.happyArray[indexPath.section];
        cell.checkMoreBtn.tag = 300 + indexPath.section; // 给cell上的Button添加tag属性
    }else if (indexPath.section == 1){
        cell.postAuthor.text = @"随手玩儿啥";
        cell.modelArray = self.happyArray[indexPath.section];
        cell.checkMoreBtn.tag = 300 + indexPath.section;// 给cell上的Button添加tag属性
    }
    [cell.checkMoreBtn addTarget:self action:@selector(checkMore:) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.selected = NO;
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 270 * _scaleY;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15 * _scaleY;
}



#pragma mark --执行HappyPlayCellDelegate协议的方法
- (void)pushToDetailViewControloler:(HappyModel *)model
{
    DetailController *detailVc = [[DetailController alloc] init];
    detailVc.happyModel = model;
    detailVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVc animated:YES];
}
#pragma mark --执行CarouselFigureDelegate协议方法
- (void)didSelectCarouselPushDetailVcWith:(CarouselFigureModel *)model
{
    DetailController *detailVc = [[DetailController alloc] init];
    detailVc.carouselModel = model;
    detailVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVc animated:YES];
}

#pragma mark --点解查看更多Button的方法
- (void)checkMore:(UIButton *)btn
{
    CheckMoreController *checkMoreVc = [[CheckMoreController alloc] init];
    int section = (int)btn.tag - 300;
    checkMoreVc.section = section;
    checkMoreVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:checkMoreVc animated:YES];
}

#pragma mark --点击三个tableViewHeader上面三个Button触发得方法
- (void)button:(UIButton *)btn
{
    SegmentController *segmentVc = [[SegmentController alloc] init];
    segmentVc.hidesBottomBarWhenPushed = YES;
    if (btn.tag >= 100 && btn.tag <= 102) {
        segmentVc.category_id = (int)btn.tag - 100 + 1;
    }
    [self.navigationController pushViewController:segmentVc animated:YES];}

@end
